<?php 
namespace ProductType\Model;

 use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Predicate\In;
	
 class ProductTypeTable
 {
     protected $tableGateway;

     public function __construct(TableGateway $tableGateway)
     {
         $this->tableGateway = $tableGateway;
     }

     public function fetchAll()
     {
         $select = $this->tableGateway->getSql()->select()->order ( array (
				'ID_PRT DESC' 
		) );
         $resultSet = $this->tableGateway->selectWith ( $select );
         $resultSet->buffer ();
         return $resultSet;
     }
     
     public function countProductType(){
     	return $this->tableGateway->select()->count();
     }
     
     public function saveProductType(ProductType $producttype,$id)
     {
     	if($producttype->activeprotype == null)
     		$producttype->activeprotype = 0;
     	$data = array(
     			'NAME_PRT' => $producttype->nameprotype ,
     			'ACTIVE_PRT' => $producttype->activeprotype ,
     	);
     
     	if ($id == 0) {
     		$this->tableGateway->insert($data);
     	}else {
     		if ($this->getProductType($id)) {
     			$this->tableGateway->update($data, array('ID_PRT' => $id));
     		} else {
     			throw new \Exception('Product id does not exist');
     		}
     	}
     }
     
     public function getProductType($id)
     {
     	$id  = (int) $id;
     	$rowset = $this->tableGateway->select(array('ID_PRT' => $id));
     	$row = $rowset->current();
     	if ($row) {
     		$row->nameprotype = $row->NAME_PRT;
     		$row->activeprotype = $row->ACTIVE_PRT;
     	}
     	return $row;
     }
     
     public function deleteProductType($id)
     {
     	$this->tableGateway->delete(array('ID_PRT' => (int) $id));
     }
 }